import Cookies from 'js-cookie';
import CryptoJS from 'crypto-js';
import {CRYPTO_KEY, EXPIRES} from '@/constants';
import Compressor from 'compressorjs';
import {Toast} from 'vant';
import { uploadFile } from '@/api/upload.js';
// 加密
export function encrypt(word, keyStr) {
  keyStr = keyStr || CRYPTO_KEY;
  let key = CryptoJS
    .enc
    .Utf8
    .parse(keyStr); // Latin1 w8m31+Yy/Nw6thPsMpO5fg==

  let srcsText = CryptoJS
    .enc
    .Utf8
    .parse(word);

  let encrypted = CryptoJS
    .AES
    .encrypt(srcsText, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    });

  return encrypted.toString();
}
// 解密
export function decrypt(word, keyStr) {
  keyStr = keyStr || CRYPTO_KEY;
  let key = CryptoJS
    .enc
    .Utf8
    .parse(keyStr); // Latin1 w8m31+Yy/Nw6thPsMpO5fg==

  let decryptText = CryptoJS
    .AES
    .decrypt(word, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    });

  return CryptoJS
    .enc
    .Utf8
    .stringify(decryptText)
    .toString();
}

export const cookie = {
  set(key, value) {
    Cookies.set(key, encrypt(JSON.stringify(value)), {expires: EXPIRES});
  },
  get(key) {
    let info = Cookies.get(key);

    if (info) {
      return JSON.parse(decrypt(info));
    }
    return false;
  },
  remove(key) {
    return Cookies.remove(key);
  }
};

export const localDB = {
  set(key, value) {
    localStorage.setItem(key, encrypt(JSON.stringify(value)));
  },
  get(key) {
    if (localStorage) {
      let info = localStorage.getItem(key);

      if (info) {
        return JSON.parse(decrypt(info));
      }
      return false;
    }
    return false;
  },
  remove(key) {
    localStorage.removeItem(key);
  },
  clear() {
    localStorage.clear();
  }
};

export const parseUrlToObject = function (urlStr) {
  const res = {};

  if (urlStr) {
    const urlParmArr = urlStr.split('?');

    if (urlParmArr.length >= 2) {
      const parmArr = urlParmArr[1].split('&');

      for (const i in parmArr) {
        const item = parmArr[i];

        if (item) {
          const keyValueArr = item.split('=');

          if (keyValueArr.length == 2) {
            if (keyValueArr[1]) {
              res[keyValueArr[0]] = keyValueArr[1];
            }
          }
        }
      }
    }
  }
  return res;
};

export const compressor = function (e) {

  var mPromise = new Promise(function (resolve,reject) {
    var file = e;

    if ('image/jpegimage/jpgimage/pngimage/svgimage/webp'.indexOf(file.type) == -1) {
      Toast.fail('选择格式错误');
      return;
    }
    let qualitySize = 0.8;

    let fileSize = file.size / 1024;

    if (fileSize / 1024 > 10) {
      Toast.fail('选择图片最大限制10M');
      return;
    }
    if (fileSize > 500) {
      if (fileSize < 2000) {
        qualitySize = 0.5;
      } else {
        qualitySize = 0.15;
      }
    }
    // eslint-disable-next-line no-new
    new Compressor(file, {
      quality: qualitySize,
      convertSize: 0,
      success(result) {
        const parms = new FormData();

        parms.append('file-upload', result, result.name);
        uploadFile(parms).then(res => {
            if (res.code === 200) {
              let mData = res.data;

              resolve(mData);
            } else {
              Toast.fail(res.message);
            }
          })
          .catch(error => {
            reject();
            console.log(error);
            });
      },
      error(err) {
        console.log(err);
        Toast.fail('图片压缩错误');
      }
    });
  });

  return mPromise;
};

export const formatDate = function(date,fmt){
  var o = {
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    "S": date.getMilliseconds() //毫秒
  };

  if (/(y+)/.test(fmt)){
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (let k in o){
    if (new RegExp("(" + k + ")").test(fmt)){
      fmt = fmt.replace(RegExp.$1,RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    }
  }
  return fmt;
};
 //格式化时间
export const confirmPicker = function(val) {
  let year = val.getFullYear();

  let month = val.getMonth() + 1;

  let day = val.getDate();

  let hour = val.getHours();

  let minute = val.getMinutes();

  let timeValue = "";

  if (month >= 1 && month <= 9) { 
    month = `0${month}`; 
  }
  if (day >= 1 && day <= 9) { 
    day = `0${day}`; 
  }
  if (hour >= 0 && hour <= 9) { 
    hour = `0${hour}`; 
  }
  if (minute >= 0 && minute <= 9) { 
    minute = `0${minute}`; 
  }
  timeValue = `${year}-${month}-${day} ${hour}:${minute}`;
  return timeValue;
};
//防抖
export function _debounce(fn, delay,that) {

  delay = delay || 200;
  let timer;

  return function () {
      let th = that;

      let args = arguments;

      if (timer) {
          clearTimeout(timer);
      }
      timer = setTimeout(function () {
          timer = null;
          fn.apply(th, args);
      }, delay);
  };
}